// 路由配置示例 - 集成404和功能开发中页面
import { createRouter, createWebHistory } from 'vue-router'

// 页面组件导入
import Home from '@/views/Home.vue'
import Visualization from '@/views/Visualization.vue' 
import DataTest from '@/views/DataTest.vue'
import NotFound from '@/views/NotFound.vue'
import UnderDevelopment from '@/views/UnderDevelopment.vue'

// 功能状态配置 - 集中管理所有功能的开发状态
const FEATURE_STATUS = {
  // 完成的功能
  '/': { isCompleted: true },
  '/visualization': { isCompleted: true },
  '/data-test': { isCompleted: true },
  
  // 开发中的功能
  '/aps-config': {
    isCompleted: false,
    featureName: 'APS系统配置中心',
    progress: 75,
    expectedDate: '2024年2月',
    description: '高级排程系统的配置和参数调优功能'
  },
  '/advanced-reports': {
    isCompleted: false,
    featureName: '高级报表分析',
    progress: 45,
    expectedDate: '2024年3月',
    description: '多维度数据分析和可视化报表功能'
  },
  '/ai-scheduling': {
    isCompleted: false,
    featureName: 'AI智能排程',
    progress: 80,
    expectedDate: '2024年1月',
    description: '基于机器学习的智能排程优化算法'
  },
  '/real-time-monitor': {
    isCompleted: false,
    featureName: '实时监控大屏',
    progress: 30,
    expectedDate: '2024年4月',
    description: '生产线实时状态监控和预警系统'
  }
}

// 路由配置
const routes = [
  // ==================== 基础路由 ====================
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页',
      requiresAuth: false
    }
  },

  // ==================== 已完成功能路由 ====================
  {
    path: '/visualization',
    name: 'Visualization',
    component: Visualization,
    meta: {
      title: '可视化控制台',
      requiresAuth: true
    }
  },
  {
    path: '/data-test',
    name: 'DataTest',
    component: DataTest,
    meta: {
      title: '数据测试',
      requiresAuth: true
    }
  },

  // ==================== 开发中功能路由 ====================
  // 方式1: 直接路由到开发中页面
  {
    path: '/aps-config',
    name: 'ApsConfig',
    component: UnderDevelopment,
    props: () => ({
      featureName: FEATURE_STATUS['/aps-config'].featureName,
      progress: FEATURE_STATUS['/aps-config'].progress,
      expectedDate: FEATURE_STATUS['/aps-config'].expectedDate
    }),
    meta: {
      title: 'APS配置中心',
      isUnderDevelopment: true
    }
  },
  {
    path: '/advanced-reports',
    name: 'AdvancedReports',
    component: UnderDevelopment,
    props: () => ({
      featureName: FEATURE_STATUS['/advanced-reports'].featureName,
      progress: FEATURE_STATUS['/advanced-reports'].progress,
      expectedDate: FEATURE_STATUS['/advanced-reports'].expectedDate
    }),
    meta: {
      title: '高级报表',
      isUnderDevelopment: true
    }
  },
  {
    path: '/ai-scheduling',
    name: 'AiScheduling',
    component: UnderDevelopment,
    props: () => ({
      featureName: FEATURE_STATUS['/ai-scheduling'].featureName,
      progress: FEATURE_STATUS['/ai-scheduling'].progress,
      expectedDate: FEATURE_STATUS['/ai-scheduling'].expectedDate
    }),
    meta: {
      title: 'AI智能排程',
      isUnderDevelopment: true
    }
  },

  // ==================== 嵌套路由示例 ====================
  {
    path: '/admin',
    name: 'AdminLayout',
    component: () => import('@/views/AdminLayout.vue'),
    meta: {
      title: '管理后台',
      requiresAuth: true,
      requiresAdmin: true
    },
    children: [
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('@/views/admin/UserManagement.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'system',
        name: 'SystemSettings',
        component: UnderDevelopment,
        props: {
          featureName: '系统设置',
          progress: 60,
          expectedDate: '2024年2月'
        },
        meta: { 
          title: '系统设置',
          isUnderDevelopment: true 
        }
      }
    ]
  },

  // ==================== 通用路由 ====================
  // 功能开发中页面（可通过参数动态配置）
  {
    path: '/under-development',
    name: 'UnderDevelopment',
    component: UnderDevelopment,
    props: route => ({
      featureName: route.query.feature || '新功能',
      progress: parseInt(route.query.progress) || 50,
      expectedDate: route.query.date || '即将发布'
    }),
    meta: {
      title: '功能开发中'
    }
  },

  // 组件演示页面
  {
    path: '/component-demo',
    name: 'ComponentDemo',
    component: () => import('@/views/ComponentDemo.vue'),
    meta: {
      title: '组件演示'
    }
  },

  // ==================== 错误页面路由 ====================
  // 404路由必须放在最后
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面不存在'
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  // 路由切换时滚动到顶部
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// ==================== 路由守卫 ====================

// 全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('路由跳转:', from.path, '->', to.path)
  
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - APS系统`
  }
  
  // 检查功能开发状态（可选的动态检查）
  if (to.path !== '/under-development' && FEATURE_STATUS[to.path]) {
    const feature = FEATURE_STATUS[to.path]
    
    if (!feature.isCompleted) {
      // 可以选择重定向到开发中页面，或者在组件中处理
      console.log(`功能 ${feature.featureName} 正在开发中`)
      
      // 方式1: 重定向到通用开发中页面
      // next({
      //   path: '/under-development',
      //   query: {
      //     feature: feature.featureName,
      //     progress: feature.progress,
      //     date: feature.expectedDate
      //   }
      // })
      // return
    }
  }
  
  // 权限检查示例
  if (to.meta?.requiresAuth) {
    const isAuthenticated = checkAuthStatus() // 检查用户认证状态
    if (!isAuthenticated) {
      next('/login')
      return
    }
  }
  
  if (to.meta?.requiresAdmin) {
    const isAdmin = checkAdminStatus() // 检查管理员权限
    if (!isAdmin) {
      next('/403') // 权限不足页面
      return
    }
  }
  
  next()
})

// 全局后置守卫
router.afterEach((to, from) => {
  // 路由跳转完成后的处理
  console.log('路由跳转完成:', to.path)
  
  // 可以在这里添加页面访问统计
  trackPageView(to.path, to.meta?.title)
})

// ==================== 辅助函数 ====================

/**
 * 检查用户认证状态
 */
function checkAuthStatus() {
  // 这里应该检查用户的登录状态
  // 例如检查localStorage中的token或调用API验证
  return localStorage.getItem('authToken') !== null
}

/**
 * 检查管理员权限
 */
function checkAdminStatus() {
  // 检查用户是否有管理员权限
  const userRole = localStorage.getItem('userRole')
  return userRole === 'admin'
}

/**
 * 页面访问统计
 */
function trackPageView(path, title) {
  // 这里可以集成Google Analytics或其他统计工具
  console.log('页面访问统计:', { path, title, timestamp: new Date() })
}

/**
 * 获取功能开发状态
 * @param {string} path - 路由路径
 * @returns {object} 功能状态信息
 */
export function getFeatureStatus(path) {
  return FEATURE_STATUS[path] || { isCompleted: true }
}

/**
 * 检查功能是否完成开发
 * @param {string} path - 路由路径
 * @returns {boolean} 是否已完成开发
 */
export function isFeatureCompleted(path) {
  const status = FEATURE_STATUS[path]
  return !status || status.isCompleted
}

/**
 * 获取所有开发中的功能
 * @returns {array} 开发中功能列表
 */
export function getUnderDevelopmentFeatures() {
  return Object.entries(FEATURE_STATUS)
    .filter(([path, status]) => !status.isCompleted)
    .map(([path, status]) => ({
      path,
      ...status
    }))
}

// ==================== 动态路由管理 ====================

/**
 * 动态添加开发中功能的路由
 * @param {string} path - 路由路径
 * @param {object} featureInfo - 功能信息
 */
export function addUnderDevelopmentRoute(path, featureInfo) {
  // 更新功能状态
  FEATURE_STATUS[path] = {
    isCompleted: false,
    ...featureInfo
  }
  
  // 动态添加路由
  router.addRoute({
    path,
    name: featureInfo.featureName.replace(/\s+/g, ''),
    component: UnderDevelopment,
    props: {
      featureName: featureInfo.featureName,
      progress: featureInfo.progress,
      expectedDate: featureInfo.expectedDate
    },
    meta: {
      title: featureInfo.featureName,
      isUnderDevelopment: true
    }
  })
}

/**
 * 将开发中功能标记为完成
 * @param {string} path - 路由路径
 * @param {component} component - 新的组件
 */
export function markFeatureAsCompleted(path, component) {
  // 更新功能状态
  if (FEATURE_STATUS[path]) {
    FEATURE_STATUS[path].isCompleted = true
  }
  
  // 移除旧路由并添加新路由
  router.removeRoute(path)
  router.addRoute({
    path,
    component,
    meta: {
      title: FEATURE_STATUS[path]?.featureName || '功能页面'
    }
  })
}

export default router

// ==================== 使用示例 ====================

/*
// 在main.js中使用
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/example.js'

const app = createApp(App)
app.use(router)
app.mount('#app')

// 在组件中使用
import { useRouter } from 'vue-router'
import { getFeatureStatus, isFeatureCompleted } from '@/router/example.js'

export default {
  setup() {
    const router = useRouter()
    
    const handleNavigation = (path) => {
      if (!isFeatureCompleted(path)) {
        const feature = getFeatureStatus(path)
        // 显示开发中提示或跳转到开发中页面
        ElMessage.warning(`${feature.featureName} 正在开发中`)
        return
      }
      
      router.push(path)
    }
    
    return {
      handleNavigation
    }
  }
}
*/
